package com.mogu.blogs.service.impl;

import com.mogu.blogs.mapper.FabuMapper;
import com.mogu.blogs.service.FabuService;
import com.mogu.blogs.utils.RedisUtils;
import com.mogu.entity.TBlog;


import com.mogu.utils.RedisUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;



@Service
public class FabuServiceImpl implements FabuService {

    @Resource
    FabuMapper fabuMapper;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public String fabu(TBlog tBlog) {

//        UUID uuid = UUID.randomUUID();
//        tBlog.setUid(uuid.toString());
        String str= RandomStringUtils.randomAlphanumeric(10);
        tBlog.setUid(str);
        tBlog.setSort(1);
        tBlog.setStatus(1);
        tBlog.setStartComment(1);

        Date date = new Date();
        tBlog.setCreateTime(date);
        tBlog.setUpdateTime(date);
        fabuMapper.fabu(tBlog);
        return "发布成功";
    }

    @Override
    public String baocun(TBlog tBlog) {

        if (tBlog.getAuthor()!=null){
            redisUtils.set(tBlog.getAuthor(),tBlog);

            return "success";
        }else {
            return "fail";
        }

    }

    @Override
    public TBlog zhanshi(String username) {
        if (username == null){
            return null;
        }else {
            JSONObject jsonObject= JSONObject.fromObject(redisUtils.get(username)); // 将数据转成json字符串
            TBlog tBlog = (TBlog)JSONObject.toBean(jsonObject, TBlog.class); //将json转成需要的对象
            /*TBlog tBlog = new TBlog();
            tBlog= (TBlog) redisUtils.get(username);*/
            return tBlog;
        }

    }
}
